package com.naodong.shenluntiku.util;

import com.naodong.shenluntiku.mvp.model.bean.BaseBean;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.shingohu.man.intergation.retrofit.NoBodyEntity;
import me.shingohu.man.mvp.IView;

/**
 * Created by hujie on 17/4/24.
 */

public class RxUtils extends me.shingohu.man.util.RxUtils {


    public static <T> Observable<T> applySchedulers(Observable<BaseBean<T>> observable, Consumer<Disposable> doOnSubscribe, Action doAfterTerminate, IView view) {

        return observable.map(new ResultFunc<>())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(doOnSubscribe)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(doAfterTerminate)
                .compose(bindToLifecycle(view));

    }


    public static <T> Observable<T> applySchedulers(Observable<BaseBean<T>> observable, IView view) {
        return observable.map(new ResultFunc<>())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> view.onRequesrStart())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(view::onRequestFinish)
                .compose(bindToLifecycle(view));
    }

    public static Observable<NoBodyEntity> applyNoBodySchedulers(Observable<NoBodyEntity> observable, IView view) {
        return observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> view.onRequesrStart())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(view::onRequestFinish)
                .compose(bindToLifecycle(view));
    }

    private static class ResultFunc<T> implements Function<BaseBean<T>, T> {

        @Override
        public T apply(@NonNull BaseBean<T> tBaseBean) throws Exception {
            if (tBaseBean == null || tBaseBean.getData() == null) {
                throw new NullPointerException("response body is null");
            }
            return tBaseBean.getData();
        }
    }
}
